use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
pub fn check_id_card(id_card_no: &str) -> String {
    let mut id:Vec<char> = id_card_no.chars().collect();
    let right="身份证号码正确";
    let wrong="身份证号码错误";
    if id.len() == 15 {
       id = sixteen(id);
    }
    if id.len() != 18 {
        return wrong.to_string();
    }
    if !check(&id) {
        return wrong.to_string();
    }
    let sex=if (id[16] as usize)%2==0 {"女"} else {"男"};
    let location=get_location(&id);
    let birth=get_birth(&id);
    return  format!("{},{},{},{}",right,sex,birth,location);

}


fn check(id: &Vec<char>) -> bool {
    let ex=vec![7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
    let mut sum=0;
    for i in 0..17 {
        if id[i]<'0' || id[i]>'9' {
            return false;
        }
        sum+=((id[i] as i32)-48)*ex[i];
    }
    let check=vec!['1','0','X','9','8','7','6','5','4','3','2'];
    return check[(sum%11) as usize]==id[17];
}
fn get_check(id: &Vec<char>)->char{
    let ex=vec![7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
    let mut sum=0;
    for i in 0..17 {
        if id[i]<'0' || id[i]>'9' {
            return ' ';
        }
        sum+=((id[i] as i32)-48)*ex[i];
    }
    let check=vec!['1','0','X','9','8','7','6','5','4','3','2'];
    return check[(sum%11) as usize];
}

fn get_location(id: &Vec<char>) -> String {
    //读取id.txt文件
    let mut file = File::open("src/id.txt").unwrap();
    //读取每行6位的行政区划代码和对应的省市区名称
    let mut buffer = String::new();
    file.read_to_string(&mut buffer).unwrap();
    let mut location = HashMap::new();
    for line in buffer.lines() {
        //如果读取到的行不为空
        if line.is_empty() {
            continue;
        }
        let mut iter = line.split_whitespace();
        let code = iter.next().unwrap();
        let name = iter.next().unwrap();
        location.insert(code.to_string(), name.to_string());
    }
    //根据前6位行政区划代码获取省市区名称
    let procode = id[0..2].iter().collect::<String>()+"0000";
    let citycode = id[0..4].iter().collect::<String>()+"00";
    let pro = location.get(&procode).unwrap();
    let city = location.get(&citycode).unwrap();
    let area = location.get(&id[0..6].iter().collect::<String>()).unwrap();
    return format!("{}-{}-{}", pro, city, area);
    //先用前2位查找省级行政区划代码·
}

fn get_birth(id: &Vec<char>) -> String {
    let year = &id[6..10].iter().collect::<String>();
    let month = &id[10..12].iter().collect::<String>();
    let day = &id[12..14].iter().collect::<String>();
    return format!("{}年{}月{}日", year, month, day);
}

fn sixteen(id: Vec<char>) -> Vec<char> {
    let mut id_18 = Vec::new();
    id_18.extend_from_slice(&id[0..6]);
    id_18.push('1');
    id_18.push('9');
    id_18.extend_from_slice(&id[6..]);
    id_18.push(get_check(&id_18));
    return id_18;
}